<?php
class ItemDetailForm extends Form{
	private $user_info=array(),$bad_words='';
	function ItemDetailForm(){
			
		if(Item::$item['display'])
		{
			$this->user_info = User::getUser(Item::$item['user_id']);
			
			if(Item::$item['have_image'])//get images  //if(Item::$item['display'] && Item::$item['img_url']!="")
			{
				Item::$item['images'] 		= Item::get_item_images(Item::$item['id']);
				//Item::$item['max_path']	= AZLib::getImageThumbMax(Item::$item['img_url'],'',1,Item::$item['img_server']);
			}
			else
			{
				Item::$item['images'] = array();
			}
			
			CGlobal::$curCategory = Item::$item['category_id'];//get current category id from item 
			
			Form::Form('ItemDetailForm');
			
			//$this->link_header("<script>MM_preloadImages('style/images/add_uncheck.gif','style/images/add_check.gif');</script>");
			
			$this->link_css('style/ItemDetail.css');
			$this->link_css('style/listItem.css');
			$this->link_css('style/aznet/jquery.lightbox.css');
			
			$this->link_js('javascript/enbac/item_detail.js');			
			$this->link_js('javascript/jquery/jquery.ifixpng2.js');
									
			$this->link_js('javascript/jquery/lightbox/jquery.lightbox.js');
			$this->link_js('javascript/jquery/packed/jquery.jeditable.js');
			$this->link_js('javascript/jquery/packed/jquery.cookie.js');
			
			$this->link_js('javascript/enbac/bbcode.js');
			$this->link_js('javascript/ZeroClipboard.js');
			
			if(User::have_permit(ADMIN_ITEM))
			{
				$this->link_css('style/admin.css');
				$this->link_js('javascript/enbac/items_list.js');
				$this->link_js('javascript/jquery/ui.datepicker.js');
				$this->link_css('style/aznet/ui.datepicker.css');	
			}
		}
	}
	
	function draw()
	{
		if (Item::$item && isset(Item::$item['display']) && Item::$item['display'])
		{
			global $display;
			
			AZLib::getCats();
			
			$item_detail 						= Item::$item;
			
			$item_detail['name_url'] 			= AZLib::safe_title($item_detail['name']);//rewrite URL

			$item_detail['modify_time'] 	= (date('Y') != date('Y',$item_detail['modify_time']))?date('H:i, d/m/Y',$item_detail['modify_time']): date('H:i, d/m',$item_detail['modify_time']);			
			$item_detail['created_time'] 		= (date('Y') != date('Y',$item_detail['created_time']))?date('H:i, d/m/Y',$item_detail['created_time']): date('H:i, d/m',$item_detail['created_time']);			
			
			$item_detail['price'] 			= AZLib::convertCurrency($item_detail['price'],$item_detail['currency_id']);
			$item_detail['price_out'] 		= AZLib::convertCurrency($item_detail['price_out'],$item_detail['currency_id']);
			
			if(isset(CGlobal::$allCategories[$item_detail['category_id']])){
				$item_detail['item_url'] = WEB_DIR.AZRewrite::formatUrl('?page=item_detail&id='.$item_detail['id'].'&ebname='.AZLib::safe_title($item_detail['name']).'&nice_name='.CGlobal::$allCategories[$item_detail['category_id']]['nice_name']);
			}
			else{	
				$item_detail['item_url'] = WEB_DIR.AZRewrite::formatUrl('?page=item_detail&id='.$item_detail['id'].'&ebname='.AZLib::safe_title($item_detail['name']));
			}
			
			//$display->add('currency_id',$item_detail['price']?CGlobal::$currency[$item_detail['currency_id']]:'');
			$display->add('currency_id',$item_detail['price'] ? 'VNĐ' : '');
			
			$item_detail['price'] 			= $item_detail['price']?number_format($item_detail['price'],0,',','.'):'Liên hệ';
			$item_detail['price_out'] 		= $item_detail['price_out']?number_format($item_detail['price_out'],0,',','.'):'';
						
			//item images
			$display->add("item_images",$item_detail['images']);
			$display->add("count_img",count($item_detail['images']));
			$display->add("images_url_root",isset($item_detail['img_server'])?'http://'.CGlobal::$img_server[(int)$item_detail['img_server']]:'');
			//END item images
			
			$this->admin_links($item_detail);			
			
			//Highlight keyword search 
			$this->highlight_searchword($item_detail);
			//END Highlight keyword search
			
			$show_error=false;
		
			if($item_detail['status'] == 2)
			{
				$show_error=true;
				
				if(User::have_permit(ADMIN_ITEM))
				{
					$display->add('modify_by',' (bởi <b>'.$item_detail['modify_user_name'].'</b> lúc <b>'.date('d/m/Y H:i',$item_detail['modify_time']).'</b>)');
				}
			}
			$display->add("show_error",$show_error);

			$link_item = "p".$item_detail['id']."/".AZLib::safe_title($item_detail['name']).".html";
			
			if(isset(CGlobal::$allCategories[$item_detail['category_id']])){
				$link_item=CGlobal::$allCategories[$item_detail['category_id']]['nice_name'].'/'.$link_item;
			}
			
			$first_img	= false;
			
			if(Item::$item['images'])
			{
				foreach (Item::$item['images'] as $img)
				{
					$first_img = $img;
					break;
				}
			}
			elseif(Item::$item['img_url'])
			{
				$first_img['i']				= 1;
				$first_img['img_server'] 	= Item::$item['img_server'];
				
				$first_img['thumb316']	 	= AZLib::getImageThumb(Item::$item['img_url'],316,0,0,  Item::$item['img_server']);
				$first_img['img_full_url']	= "http://".CGlobal::$img_server[Item::$item['img_server']].Item::$item['img_url'];
				$first_img['max_path']		= AZLib::getImageThumbMax(Item::$item['img_url'],'',1,Item::$item['img_server']);
			}
			
			
			$display->add('first_img',$first_img);
			  
			if($item_detail['status'] == 1){
				$display->add('json_item',$item_detail['id']);
			}
			else{
				$display->add('json_item',0);
			}

			//end list ly do khoa topic
			
			//for view images
			$display->add("request_uri", CGlobal::$request_uri);//Current url
			$display->add("url_flash_xml",urlencode('ebxml.php?act=item&code=tiltviewer_gallery&item_id='.$item_detail['id']));
			//END for view images			
			$display->add("msg",$this->showFormErrorMessages(1,"THÔNG BÁO"));
			
			$arr = $this->process_description($item_detail);
			
			$item_detail['brief'] 		= $arr['filter_brief'];
			$item_detail['description'] = $arr['filter_des'];
			
			/*
			$item_detail['description'] = preg_replace('#(<[/]?img.*>)#iU', '', html_entity_decode($item_detail['description']));
			$item_detail['description'] = preg_replace("/\\[([\s]*[0-9]{1,2}[\s]*)\]/eis", "\$this->embeded('$1')",$item_detail['description']);
			
			$item_detail['description'] = preg_replace('/<a[\s]*(.*)[\s]*href=[\'"](.*)[\'"][\s]*[^>]*[\s]*>(.*)<\/a>/eisU', "\$this->filter_link('$2','$3')",   $item_detail['description']);*/
								      															
			$display->add('is_admin',(int)(!User::is_block() && User::have_permit(ADMIN_USER)));
					
			$display->add("item_info",$item_detail);
			
			$display->add("item_id",$item_detail['id']);
		  	
			//$display->add("share_url", urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']));
			
			$cat_url 	= '';
			$cat_name 	= '';
			
			if(CGlobal::$curLevel2Cat){
				$cat_url 	= "c".CGlobal::$curLevel2Cat['id']."/".CGlobal::$curMainCat['ebname']."-".CGlobal::$curLevel2Cat['ebname'];
				$cat_name 	= CGlobal::$curLevel2Cat['name'];
			}
			elseif(CGlobal::$curMainCat){
				$cat_url 	= "c".CGlobal::$curMainCat['id']."/".CGlobal::$curMainCat['ebname'];
				$cat_name 	= CGlobal::$curMainCat['name'];
			}
			$display->add("cat_url", $cat_url);
			$display->add("cat_name", $cat_name);
			
			$display->add("cat_name", $cat_name);
			
			
			if(isset($_SERVER['REQUEST_URI'])){
				$display->add("http_referer", $_SERVER['REQUEST_URI']);
			}
			else{
				$display->add("http_referer", "");
			}
			
			/*//if(isset($_SERVER['HTTP_REFERER']) && eregi('enbac.com/c', $_SERVER['HTTP_REFERER'])){
			if(isset($_SERVER['HTTP_REFERER']) && eregi(WEB_ROOT.'c', $_SERVER['HTTP_REFERER'])){
				$display->add("ref_url", $_SERVER['HTTP_REFERER']);
			}
			else{
				$display->add("ref_url", $cat_url);
			}
			
			//$display->add("go_back", (isset($_SERVER['HTTP_REFERER']) && eregi('enbac.com/c', $_SERVER['HTTP_REFERER'])));
			$display->add("go_back", (isset($_SERVER['HTTP_REFERER']) && eregi(WEB_ROOT.'c', $_SERVER['HTTP_REFERER'])));*/

			
			
			
			
			
			
			####################################################################################################################################################################################	
			//Rating product
			$display->add('ranking',AZLib::getRank($item_detail,true));
			
			$display->add('login',(int)User::is_login());
			$display->add('rate_num',$item_detail['rate_num']);
			$display->add('_rank',number_format($item_detail['rank'],1,'.',','));
			$display->add('_f_rank',number_format($item_detail['f_rank'],1,'.',','));
			$display->add('_d_rank',number_format($item_detail['d_rank'],1,'.',','));
			$display->add('_u_rank',number_format($item_detail['u_rank'],1,'.',','));
			
			if($item_detail['f_rank'])
				$f_rank=number_format($item_detail['f_rank'],1,'.',',');
			else 
				$f_rank=0;
				
			$display->add('f_rank_',round($item_detail['f_rank']));
			$display->add('f_rank',$f_rank);
			$display->add('f_rate_num',$item_detail['f_rate_num']);
			
			if(User::have_permit(ADMIN_ITEM) || (User::is_login() && !DB::select("item_rating","type=0 AND user_id=".User::id()." AND item_id=".$item_detail['id']))){
				$display->add('block_f_rank',1);
			}
			else{
				$display->add('block_f_rank',0);
			}
			
			if($item_detail['d_rank'])
				$d_rank=number_format($item_detail['d_rank'],1,'.',',');
			else 
				$d_rank=0;
			
			$display->add('d_rank_',round($item_detail['d_rank']));
			$display->add('d_rank',$d_rank);
			$display->add('d_rate_num',$item_detail['d_rate_num']);
			
			if(User::have_permit(ADMIN_ITEM) || (User::is_login() && !DB::select("item_rating","type=1 AND user_id=".User::id()." AND item_id=".$item_detail['id']))){
				$display->add('block_d_rank',1);
			}
			else{
				$display->add('block_d_rank',0);
			}
			
			if($item_detail['u_rank'])
				$u_rank=number_format($item_detail['u_rank'],1,'.',',');
			else 
				$u_rank=0;
			
			$display->add('u_rank_',round($item_detail['u_rank']));
			$display->add('u_rank',$u_rank);
			$display->add('u_rate_num',$item_detail['u_rate_num']);
			
			if(User::have_permit(ADMIN_ITEM) || (User::is_login() && !DB::select("item_rating","type=2 AND user_id=".User::id()." AND item_id=".$item_detail['id']))){
				$display->add('block_u_rank',1);
			}
			else{
				$display->add('block_u_rank',0);
			}
			//End Rating product
			####################################################################################################################################################################################	
			
			
			
			
			
			$display->output("ItemDetail");
		}
		else{
			$content = 'Sản phẩm này hiện không tồn tại.';
			
			if(Item::$item && isset(Item::$item['status']) && isset(Item::$item['category_id']) && Item::$item['category_id'] && isset(CGlobal::$allCategories[Item::$item['category_id']]) ){
				$ebname = CGlobal::$allCategories[Item::$item['category_id']]['ebname'];
				
				$pid = CGlobal::$allCategories[Item::$item['category_id']]['parent_id'];
				
				if($pid && isset(CGlobal::$allCategories[$pid])){
					$ebname = CGlobal::$allCategories[$pid]['ebname']."-".$ebname;
					
					$pid = CGlobal::$allCategories[$pid]['parent_id'];
				
					if($pid && isset(CGlobal::$allCategories[$pid])){
						$ebname = CGlobal::$allCategories[$pid]['ebname']."-".$ebname;
					}
				}
				
				//header("HTTP/1.0 404 Not Found");
				$content .= " Click <a href='".WEB_DIR."c".Item::$item['category_id']."/$ebname'>vào đây</a> để xem các sản phẩm liên quan.";
			}
			elseif(Item::$item && isset(Item::$item['status']) && isset(Item::$item['level_1_catid']) && Item::$item['level_1_catid'] && isset(CGlobal::$allCategories[Item::$item['level_1_catid']]) ){
				$ebname = CGlobal::$allCategories[Item::$item['level_1_catid']]['ebname'];
				
				//header("HTTP/1.0 404 Not Found");
				$content .= " Click <a href='".WEB_DIR."c".Item::$item['level_1_catid']."/$ebname'>vào đây</a> để xem các sản phẩm liên quan.";
			}
			else{
				$content .= " Click <a href='".WEB_DIR."'>vào đây</a> để trở về Trang chủ.";
			}
			
			AZLib::show_error_mes($content);
		}
	}
	
	function embeded($i){
		$i = (int)$i;
		return isset(Item::$item['images'][$i])?'<img alt="Ảnh số '.$i.(Item::$item['images'][$i]['sold']?' (đã bán)':'').'" onclick="jQuery(\'#eb_thumb_'.$i.'\').trigger(\'click\');" style="cursor:pointer;margin:2px" title="Ảnh số '.$i.(Item::$item['images'][$i]['title']?': '.Item::$item['images'][$i]['title']:'').(Item::$item['images'][$i]['sold']?' (đã bán)':'').'" src="http://'.CGlobal::$img_server[Item::$item['images'][$i]['img_server']].'thumb_w/180/'.Item::$item['images'][$i]['img_url'].'" width="180" class="lazyload"/>':'';
	}
	
	function filter_link($link,$text){
		if($text=AZLib::trimSpace(AZLib::plainText($text))){
			$text=AZLib::strippedLink($text);
			if(strpos($link,'http://enbac.com')===0 || strpos($link,'http://www.enbac.com')===0 || strpos($link,'http://')===false){
				return "<a href=\"$link\" target=\"_blank\">$text</a>";
			}
			return "<a href=\"$link\" rel=\"nofollow\" target=\"_blank\">$text</a>";
		}
		return '';
	}
	
	function process_description($item_detail)
	{
		if(!isset($item_detail["filter_des"]) || $item_detail["filter_des"]=="")
		{
			################################################################################################################################
			//$filter_des = preg_replace('#(<[/]?img.*>)#iU', '', html_entity_decode($item_detail['description']));
			$filter_des = preg_replace('#(<[/]?img.*>)#iU', '', html_entity_decode($item_detail['description'], ENT_QUOTES, "UTF-8"));
			$filter_des = preg_replace('#(<[/]?iframe.*>.*</iframe>)#iU', '', $filter_des);
			//$filter_des = preg_replace('#(<[/]?script.*>.*</script>)#iU', '', $filter_des);
			//$filter_des = preg_replace('#(<[/]?style.*>.*</style>)#iU', '', $filter_des);
			
			//Loại bỏ thẻ CDATA
			// <![CDATA[
			//window.location='http://otothegioi.vn/raovat/HOT/Honda%20Accord%202.0%20Model%202011/re.html';
			// ]]>
			//$filter_des = str_replace(array('<![CDATA[',']]>'), "", $filter_des);
			//$filter_des = str_replace(array('window.location'), "", $filter_des);
			//TuanNK edit 2010.08.17
			
			//$filter_des = str_replace(array('>','<'), array("&gt;","&lt;"), $filter_des);
			$filter_des = strip_tags($filter_des, '<p><a><span><table><tr><td><th><br><strong><b><i><em><li><ol><ul><hr><u><font><strike>');
			
			$filter_des = preg_replace("/\\[([\s]*[0-9]{1,2}|100[\s]*)\]/eis", "\$this->embeded('$1')",$filter_des);
			$filter_des = preg_replace('/<a[\s]*(.*)[\s]*href=[\'"](.*)[\'"][\s]*[^>]*[\s]*>(.*)<\/a>/eisU', "\$this->filter_link('$2','$3')", $filter_des);
			################################################################################################################################
			
			
			################################################################################################################################
			$filter_brief = preg_replace('#(<[/]?img.*>)#iU', '', html_entity_decode($item_detail['brief'], ENT_QUOTES, "UTF-8"));
			$filter_brief = preg_replace('#(<[/]?iframe.*>.*</iframe>)#iU', '', $filter_brief);
			
			$filter_brief = strip_tags($filter_brief, '<p><a><span><table><tr><td><th><br><strong><b><i><em><li><ol><ul><hr><u><font><strike>');
			
			$filter_brief = preg_replace("/\\[([\s]*[0-9]{1,2}|100[\s]*)\]/eis", "\$this->embeded('$1')",$filter_brief);
			$filter_brief = preg_replace('/<a[\s]*(.*)[\s]*href=[\'"](.*)[\'"][\s]*[^>]*[\s]*>(.*)<\/a>/eisU', "\$this->filter_link('$2','$3')", $filter_brief);
			################################################################################################################################
			
			if(MEMCACHE_ON)
			{
				$item_memcache 					= AZMemcache::do_get("item:{$item_detail["id"]}");
				$item_memcache["filter_brief"] 	= $filter_brief;
				$item_memcache["filter_des"] 	= $filter_des;
				
				AZMemcache::do_put("item:{$item_detail["id"]}",$item_memcache);
			}
			
			return array(
							'filter_brief' => $filter_brief,
							'filter_des' 	=> $filter_des
						);
		}
		else
		{
			return array(
							'filter_brief'  => $item_detail["filter_brief"],
							'filter_des' 	=> $item_detail["filter_des"]
						);
		}
	}
	 
	function highlight_searchword(){
		global $display;
		$keywords=AZLib::cleanHtml(Url::get('keywords',''));
		$highlight='';
		if($keywords){
			$highlight=$str_search = str_replace( array('+','/','|','-','*') , "", $keywords );
			$highlight = AZLib::trimSpace($highlight);
	
			$highlight = str_replace( "'" , '', $highlight );
			$highlight = str_replace( "&#39;" , '', $highlight );
			$highlight = str_replace( "&quot;" , '', $highlight );
		}
		
		if($highlight){
			$arr=explode(' ',$highlight);	
			
			if($arr){	
				$highlight="";
				foreach ($arr as $word){	
					$highlight=($highlight?$highlight.', ':'')."'$word'";	
				}
			}
		}
		$display->add('highlight',$highlight);
	}
	
	function admin_links(&$item_detail){//Menu admin
		global $display;
		
		$edit_link		='';
		$del_link		='';
		$del_link_item 	= '';

		if(!User::is_block() && User::have_permit(ADMIN_ITEM))
		{
			$edit_link	= WEB_DIR.AZRewrite::formatUrl('?page=post_item&cmd=edit&id='.$item_detail['id']);
			
			if(Item::$item['status'] !=-1 )
			$del_link	= 1;
			
			$display->add("have_permit" , 1);
			
			$del_link_item = ' [ <a class="delete" href="javascript:void(0)" title="Xóa sản phẩm này!" onclick="del_item('.$item_detail['id'].');return false;">Xóa</a> ] ';

			if($item_detail['status'] == -1)
			{
				$this->setFormError('','<center><font color=red>Sản phẩm đã bị xoá (bởi <b>'.$item_detail['del_user'].'</b> lúc <b>'.date('d/m/Y H:i',$item_detail['del_time']).'</b>)</font></center>');
			}
			elseif($item_detail['status'] == 2){//Sản phẩm bị ẩn
				$this->setFormError('','<center><font color=red>Sản phẩm đang bị ẩn (bởi <b>'.$item_detail['modify_user_name'].'</b> lúc <b>'.date('d/m/Y H:i',$item_detail['modify__time']).'</b>)</font></center>');			
			}
		}
		
		$display->add("edit_link" , 	$edit_link);
		$display->add("del_link" , 		$del_link);
		$display->add("del_link_item" , $del_link_item);
	}						
	
	static function get_tag_search($cat_id = 0, $sub_cat_id = 0, $update_cache = 0, $delcache = false){		
		$tag_search = array();
		$subDir = 'tag_search';

		$sql = 'SELECT id, keywords, hit, cat_id FROM tag_search WHERE cat_id IN ('.$cat_id.','.$sub_cat_id.') ORDER By hit DESC';
		$tag_search = AZCache::cache($sql,__LINE__.__FILE__,86400,$update_cache,'',$subDir,$delcache);		
		if($tag_search && !$delcache){						
			return $tag_search;
		}
		return $tag_search;
	}
	
	static function filter_tag_search($string_input,$show_tag_search=false,$html_entity_decode=false){
	
		$set_tag_search = '';
		$arr_tag_search = self::get_tag_search(Item::$item['category_id'],Item::$item['level_1_catid']);	
		foreach($arr_tag_search as $value_tagsearch){			
			$set_tag_search .= ($set_tag_search?', ':'').$value_tagsearch["keywords"];
		}	
						
		$url_root = WEB_ROOT.'search?keywords=';				
		
		if(!$string_input || !$set_tag_search) {
			return false;
		}
	
		if($html_entity_decode){
			$html_entity_decode=html_entity_decode($html_entity_decode, ENT_QUOTES, "UTF-8");
		}
		$set_tag_search 	= trim( mb_strtolower($set_tag_search, mb_detect_encoding($set_tag_search)) );
		$string_input 	= trim( strip_tags( mb_strtolower($string_input, mb_detect_encoding($string_input)) ) );
		
		//explode to array
		$tag_search_list = explode(',', $set_tag_search);
		$tag_search_list = array_map('trim', $tag_search_list);
		$filtro 		= str_replace('||','|',implode('|', $tag_search_list));			
		$filtro 	  	= AZLib::delDoubleSpace(AZLib::trimSpace($filtro));		
		$filtro	 		= preg_replace("/\/|\*/is", "", $filtro); //loai ky tu: / *		
		$string_input 	= AZLib::delDoubleSpace(AZLib::trimSpace($string_input));						
		
		if($show_tag_search){
			preg_match_all("/($filtro)/is",$string_input,$matches);				
			$set_tag_search = "";
			$arr_temp=array();
			foreach($matches[0] as $value){
				if(!in_array($value,$arr_temp)){
					$set_tag_search .= ($set_tag_search?', ':'').'<a target="_blank" href="'.$url_root.urlencode($value).'">'.$value.'</a>';
					$arr_temp[]=$value;
				}
		    }
		    return $set_tag_search;		
		}
		else{
			if(preg_match("/($filtro)/is",$string_input)){
				return true;
			}
		}
		
		return false;				
	}
}
?>